package com.nexgo.payment.trans.scansale;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.nexgo.data.entity.RecvData;
import com.nexgo.data.json.JsonRecData;
import com.nexgo.data.json.JsonTools;
import com.nexgo.data.json.bean.JsonBody;
import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.aop.annotation.TransCondition;
import com.nexgo.payment.constrant.CardMode;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.trans.AbsScanTransPresenter;
import com.nexgo.payment.trans.TransFlow;
import com.nexgo.payment.util.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 扫码支付
 * Created by wanghongyang on 2017/9/1.
 */
@TransCondition
@TransFlow
public class ScanSalePresenter extends AbsScanTransPresenter implements ScanSaleContract.Presenter {
    private final Logger mLog = LoggerFactory.getLogger(ScanSalePresenter.class.getSimpleName());

    private final ScanSaleContract.View mView;
    private static int mQueryTimes = 1;
    private boolean mScanFlag;
    private String mChannel;
    private boolean mIsScanNext = false;



    public ScanSalePresenter(@NonNull ScanSaleContract.View view, @NonNull DataSource repository,boolean scanFlag,String channel) {
        super(view, repository);
        mView = checkNotNull(view);
        mScanFlag = scanFlag;
        mChannel = channel;
        mView.setPresenter(this);
    }


    @Override
    protected TransData getTransData() {
        TransData transData = new TransData();
        if(mScanFlag){
            transData.setTransType(TransType.SCAN_ORDER);
            transData.setScanChannel(mChannel);
            transData.setTemporary("1");//区分下单和扫码
        }else {
            transData.setTransType(TransType.SCAN_SALE);
            transData.setTemporary("0");//区分下单和扫码
        }
        transData.setIsAutoQuery(true);

        return transData;
    }

    @Override
    protected void onTransQueryOrCancel(JsonRecData recvData) {
//        处理48域解析得到订单号
        mLog.debug(" onTransQueryOrCancel mQueryTimes {}",mQueryTimes);
        if(recvData != null && recvData.getREQ_BODY() !=null && recvData.getREQ_BODY().getDECRYPT() !=null) {
            JsonBody jsonBody = JsonTools.fromJson(recvData.getREQ_BODY().getDECRYPT(), JsonBody.class);
            mTransData.setTraceCode(jsonBody.getSys_order_no());
        }

        if( mQueryTimes < 3) {
            postMainThread(() -> mView.showNeedScanQuery(mQueryTimes));
        }else{
            mQueryTimes = 1;
            if(mTransData.getTemporary().equals("0")) {//三次到查询后 扫码发撤销，下单发取消
                mTransData.setTransType(TransType.SCAN_VOID);
                postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.scan_void_start)));
            }else{
                mTransData.setTransType(TransType.SCAN_CANCEL);
                postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.scan_canel_start)));
            }
        }
    }


    @Override
    protected void onTransSuccess(RecvData recvData) {
        postMainThread(() -> mView.quitTrans());
    }

    @Override
    protected void onFirstAction() {
            postMainThread(() -> mView.showInputAmount(mTransData));
    }

    @Override
    protected void inputAmountNext(Object data) {
        mTransData.setAmount(StringUtils.leftPad((String) data, 12, '0'));
        if(mScanFlag){
            postMainThread(() -> mView.showOnlineProc(mTransData,App.sContext.getString(R.string.scan_order_scan)));
        }
        else{
            postMainThread(() -> mView.showScanFragment());
//            postMainThread(() -> mView.showInputPayCode());
        }
    }
    @Override
    protected void inputTraceCodeNext(Object data){
        String payCode = (String) data;
        if (TextUtils.isEmpty(payCode)){
            //跳去扫码
            postMainThread(() -> mView.showScanFragment());
            return;
        }
        String str ;
        int i = Integer.parseInt(payCode.substring(0,2));
        if( i >= 13 && i <= 17){  //微信
            str = "01";
        }else if( i >= 20 && i <= 29){  // 支付宝
            str = "02";
        }else if( i == 10 || i == 62){  //银联
            str = "03";
        }else{
            postMainThread(() -> mView.showTradeFail(App.sContext.getString(R.string.scan_code_error)));
            return;
        }
        mLog.debug("str {}",str);
        mTransData.setScanChannel(str);
        mTransData.setPayCodeNo(payCode);
        mTransData.setCardMode(CardMode.SCAN);
        postMainThread(() -> mView.showOnlineProc(mTransData,null));
    }
	
    @Override
    public void ShowQueryScan(boolean isFirstTime ) {
        if(isFirstTime){
            mQueryTimes = 1;
        }else{
            mQueryTimes ++ ;
        }
        mTransData.setTransType(TransType.SCAN_QUERY);
        postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.scan_query_start)));
    }

    @Override
    public void ShowCancelScan() {
        mTransData.setTransType(TransType.SCAN_CANCEL);
        postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.scan_canel_start)));
    }

    @Override
    public void ShowVoidScan() {
//        postMainThread(() -> mView.showOnlineCancelProc(mTransData));
        mTransData.setTransType(TransType.SCAN_VOID);
        postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.scan_void_start)));
    }

    @Override
    public void ShowSelectChannel(String Channel) {
        mTransData.setScanChannel(Channel);
        postMainThread(() -> mView.showInputAmount(mTransData));
    }

    @Override
    protected void onShowScanOrderUrl(JsonRecData recvData) {
        if(recvData.getREQ_BODY() != null && recvData.getREQ_BODY().getDECRYPT() != null) {
            JsonBody jsonBody = JsonTools.fromJson(recvData.getREQ_BODY().getDECRYPT(), JsonBody.class);
            if (jsonBody.getCode_url() == null) {
                postMainThread(() -> mView.showTradeFail(App.sContext.getString(R.string.url_get_fail)));
            } else {
                mTransData.setPayCodeNo(jsonBody.getCode_url());
                mTransData.setTraceCode(jsonBody.getSys_order_no());
                mQueryTimes = 0;
                postMainThread(() -> mView.showScanOrderFragment(mTransData));
            }
        }else{
            postMainThread(() -> mView.showTradeFail(App.sContext.getString(R.string.url_get_fail)));
        }
    }

    @Override
    protected void showScanUrlNext() {
        mTransData.setCardMode(CardMode.SCAN);
        mTransData.setEntryMode(getEntryMode());  //22域
        mScanFlag = false;
        mTransData.setTransType(TransType.SCAN_QUERY);
        mQueryTimes ++;
        postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.scan_query_start)));
    }

    @Override
    public void inputScanNext(Object scanData) {
        String payCode = (String) scanData;
        if (TextUtils.isEmpty(payCode)){
            //跳去扫码
            postMainThread(() -> mView.showScanFragment());
            return;
        }
        //判断是否为正常付款码，并判断交易渠道
        String str ;
        int i = Integer.parseInt(payCode.substring(0,2));
        if( i >= 13 && i <= 17){  //微信
            str = "01";
        }else if( i >= 20 && i <= 29){  // 支付宝
            str = "02";
        }else if( i == 10 || i == 62){  //银联
            str = "03";
        }else{
            postMainThread(() -> mView.showTradeFail(App.sContext.getString(R.string.scan_code_error)));
            return;
        }

        mTransData.setScanChannel(str);
        mTransData.setPayCodeNo(payCode);
        mTransData.setCardMode(CardMode.SCAN);

        mIsScanNext = true; //记录扫码后的状态

//        mLog.debug("inputScanNext");
//        postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.scan_sale_start)));
    }

    @Override
    public void showOnScanNextAndRestart() {
        if (!mIsScanNext) return;
            postMainThread(() -> mView.showOnlineProc(mTransData, App.sContext.getString(R.string.scan_sale_start)));
            mIsScanNext = false;
    }

}
